<template>
  <el-card class="main-card">
    <div class="split-container">
      <!-- 左侧图片和操作区 -->
      <div class="left-section">
        <div class="image-container">
          <el-button
            size="default"
            type="default"
            icon="ele-ArrowLeft"
            @click="handlePrev"
            class="image-nav-btn prev-btn"
          />

          <el-image
            :src="processedImageUrl"
            :preview-src-list="[processedImageUrl]"
            class="main-image"
            fit="contain"
            :key="item.id"
            hide-on-click-modal
          />

          <el-button
            size="default"
            type="default"
            icon="ele-ArrowRight"
            @click="handleNext"
            class="image-nav-btn next-btn"
          />
        </div>
      </div>

      <!-- 右侧表单面板 -->
      <div class="right-section">
        <div class="form-container">
          <div class="header-info">
            <el-tag class="type-tag">{{ item.class_type || item.type }}</el-tag>
            <el-text class="panel-id">{{ item.panelId}}</el-text>
              <el-switch
                v-model="localItem.use"
                inline-prompt
                :active-text="$t('message.common.yes')"
                :inactive-text="$t('message.common.no')"
                @change="handleUseChange"
              />
            <el-button size="default" type="danger" @click="handleRemove" icon="Delete">
              {{ $t('message.common.delete') }}
            </el-button>
          </div>

          <el-input
            v-model="localItem.customize_name"
            :placeholder="$t('message.random.customizeName')"
            clearable
            class="custom-name-input"
            @input="handleCustomNameChange"
          />

          <el-input
            v-model="localItem.tags"
            type="textarea"
            :rows="4"
            resize="none"
            @input="handleTagsChange"
            class="tags-textarea"
            placeholder="Tags content"
          />

          <div class="inline-switches">
            <div class="switch-item">
              <el-text class="switch-label">{{ $t('message.random.favorite') }}:</el-text>
              <el-switch
                v-model="localItem.favorite"
                inline-prompt
                :active-text="$t('message.common.yes')"
                :active-value="1"
                :inactive-value="0"
                :inactive-text="$t('message.common.no')"
                @change="handleFavoriteChange"
                size="default"
              />
            </div>
            <div class="switch-item">
              <el-text class="switch-label">{{ $t('message.random.disliked') }}:</el-text>
              <el-switch
                v-model="localItem.disliked"
                inline-prompt
                :active-value="1"
                :inactive-value="0"
                :active-text="$t('message.common.yes')"
                :inactive-text="$t('message.common.no')"
                @change="handleDislikedChange"
                size="default"
              />
            </div>
            <div class="inline-rating">
              <el-rate
                v-model="localItem.rating"
                show-score
                :max="10"
                allow-half
                clearable
                score-template="{value}"
                @change="handleRatingChange"
                size="default"
              />
            </div>
            <el-text>{{ item.id }}</el-text>
          </div>
       <div class="action-buttons">
          <el-scrollbar style="width: fit-content;display: flex;">
            <el-button
              size="default"
              type="primary"
              icon="MagicStick"
              @click="handleRandom"
            >
              {{ $t(`message.random.random${typeCapitalized}`) }}
            </el-button>

            <el-popover placement="top" :width="300" trigger="click">
              <template #reference>
                <el-button
                  size="default"
                  type="primary"
                  style="min-width: 80px;"
                >
                  {{ randomConfig.value[0] }}-{{ randomConfig.value[1] }}
                </el-button>
              </template>
              <div>
                <el-slider
                  style="width:250px;margin-left: 10px;"
                  :step="0.5"
                  v-model="localRandomConfig.value"
                  range
                  show-stops
                  :min="0"
                  :max="10"
                  @change="handleRangeChange"
                />
              </div>
            </el-popover>
            <el-button
              size="default"
              type="info"
              @click="handleMoreAction('update-item')"
              icon="Check"
              class="apply-btn"
            >
              {{ $t('message.random.applyChange') }}
            </el-button>
            <el-button
              size="default"
              type="default"
              icon="Copy"
              @click="handleMoreAction('copy')"
            >
              {{ $t('message.random.copyInfo') }}
            </el-button>
            <el-button
              size="default"
              type="default"
              icon="Box"
              @click="handleMoreAction('update-image')"
            >
              {{ $t('message.random.replacePreview') }}
            </el-button>
            <el-button
              size="default"
              type="danger"
              icon="Delete"
              @click="handleClear"
            >
              {{ $t('message.common.clear') }}
            </el-button>
          </el-scrollbar>
        </div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue';
import { useExPrompt } from '@renderer/stores/useExPrompt';
import { useConfigStore } from '@renderer/stores/configStore';
import type { PromptItem, RandomConfig } from '@renderer/stores/useExPrompt';

const exPromptStore = useExPrompt();
const configStore = useConfigStore();

// 只接收panelId作为参数
const props = defineProps<{
  panelId: string;
}>();

// 向父组件传递事件
const emit = defineEmits<{
  (e: 'on-random', panelId: string, type: string): void;
  (e: 'on-clear', panelId: string): void;
  (e: 'on-more-action', panelId: string, type: string, action: string): void;
  (e: 'on-prev', panelId: string, type: string): void;
  (e: 'on-next', panelId: string, type: string): void;
  (e: 'on-remove', panelId: string): void;
}>();

// 存储当前item的响应式变量
const currentItem = ref<PromptItem & { class_type?: string }>({
  id: '',
  panelId: props.panelId,
  type: '',
  name: '',
  customize_name: '',
  image: '',
  tags: '',
  rating: 0,
  favorite: 0,
  disliked: 0,
  use: true
});

// 深度监听store中对应item的变化
watch(
  () => exPromptStore.items.find(i => i.panelId === props.panelId),
  (newVal) => {
    if (newVal) {
      // 关键：通过替换整个对象触发响应式更新
      currentItem.value = { ...newVal };
    }
  },
  { deep: true, immediate: true } // 深度监听 + 立即执行
);

// 提供给模板使用的item
const item = computed(() => currentItem.value);

// 本地副本用于表单双向绑定
const localItem = ref<PromptItem & { class_type?: string }>({ ...item.value });

// 监听item变化并更新本地副本
watch(item, (newVal) => {
  localItem.value = { ...newVal };
}, { deep: true });

// 响应式获取随机配置
const randomConfig = computed<RandomConfig>(() => {
  return exPromptStore.getRandomConfigByPanelId(props.panelId);
});

// 本地副本用于滑块双向绑定
const localRandomConfig = ref<RandomConfig>({ ...randomConfig.value });

watch(randomConfig, (newVal) => {
  localRandomConfig.value = { ...newVal };
}, { deep: true });

// 图片URL计算 - 确保id变化时更新
const processedImageUrl = computed<string>(() => {
  if (!item.value.id) return '';
  return configStore.comfyProxyImage(`file://${configStore.config.imagesPath}\\collections\\${item.value.id}.webp`)
});

// 类型名首字母大写
const typeCapitalized = computed(() => {
  const type = item.value.type;
  return type.charAt(0).toUpperCase() + type.slice(1);
});

// 事件处理方法保持不变
const handleRandom = () => {
  emit('on-random', props.panelId, item.value.type);
};

const handleClear = () => {
  emit('on-clear', props.panelId);
};

const handleMoreAction = (action: string) => {
  emit('on-more-action', props.panelId, item.value.type, action);
};

const handlePrev = () => {
  emit('on-prev', props.panelId, item.value.type);
};

const handleNext = () => {
  emit('on-next', props.panelId, item.value.type);
};

const handleRemove = () => {
  emit('on-remove', props.panelId);
};

// 数据更新方法保持不变
const handleCustomNameChange = (value: string) => {
  exPromptStore.updateItemByPanelId({
    panelId: props.panelId,
    customize_name: value
  });
};

const handleTagsChange = (value: string) => {
  exPromptStore.updateItemByPanelId({
    panelId: props.panelId,
    tags: value
  });
};

const handleRatingChange = (value: number) => {
  exPromptStore.updateItemByPanelId({
    panelId: props.panelId,
    rating: value
  });
};

const handleFavoriteChange = (value: number) => {
  exPromptStore.updateItemByPanelId({
    panelId: props.panelId,
    favorite: value
  });
};

const handleDislikedChange = (value: number) => {
  exPromptStore.updateItemByPanelId({
    panelId: props.panelId,
    disliked: value
  });
};

const handleUseChange = (value: boolean) => {
  exPromptStore.updateItemByPanelId({
    panelId: props.panelId,
    use: value
  });
};

const handleRangeChange = (value: [number, number]) => {
  exPromptStore.updateRandomConfigByPanelId({
    panelId: props.panelId,
    value
  });
};
</script>

<style scoped>
/* 样式保持不变 */
.main-card {
  border-radius: 12px;
  box-shadow: var(--next-box-shadow-dark);
  border: none;
  background-color: var(--el-color-white);
}

.split-container {
  display: flex;
  gap: 24px;
  align-items: flex-start;
}

.left-section {
  flex: 1;
  min-width: 280px;
  max-width: 400px;
  display: flex;
  flex-direction: column;
}

.image-container {
  height: 300px;
  width: 100%;
  background-color: var(--el-fill-color-light);
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  position: relative;
}

.main-image {
  max-width: 100%;
  height: 300px;
  object-fit: contain;
  transition: all 0.3s ease;
}

.image-nav-btn {
  position: absolute;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.2);
  box-shadow: var(--next-box-shadow-dark);
  z-index: 10;
  padding: 0;
  opacity: 0.7;
  transition: all 0.2s;
}

.image-nav-btn:hover {
  opacity: 1;
  transform: scale(1.1);
}

.prev-btn {
  left: 12px;
}

.next-btn {
  right: 12px;
}

.right-section {
  flex: 1;
  min-width: 280px;
}

.form-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.header-info {
  display: flex;
  align-items: center;
  gap:10px;
}

.type-tag {
  background-color: var(--el-fill-color-light);
  color: var(--el-text-color-regular);
  border: none;
  padding: 3px 10px;
  font-size: 13px;
}

.panel-id {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  font-family: monospace;
}

.custom-name-input {
  width: 100%;
  --el-input-height: 34px;
}

.tags-textarea {
  width: 100%;
  font-family: 'JetBrains Mono', monospace;
  font-size: 13px;
  resize: vertical;
  min-height: 90px;
  --el-input-height: auto;
}

.inline-switches {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
  padding: 8px 0;
}

.switch-item {
  display: flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
}

.switch-label {
  color: var(--el-text-color-placeholder);
  font-size: 13px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.apply-btn, .remove-btn {
  flex: 1;
}

@media (max-width: 992px) {
  .split-container {
    flex-direction: column;
    gap: 16px;
  }

  .left-section, .right-section {
    max-width: 100%;
    width: 100%;
  }

  .image-container {
    height: 320px;
  }
}

@media (max-width: 576px) {
  .main-card {
    padding: 12px;
  }

  .image-container {
    height: 240px;
  }

  .primary-controls, .quick-actions, .action-buttons {
    flex-direction: column;
  }

  .inline-switches {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
